using System;
using System.Text;
using System.Web.UI;

using AjaxPro;
using ECCIT.Web.Configuration;

namespace ECCIT.Web.UI
{
	/// <summary>
	/// Summary description for ELPPage.
	/// </summary>
	public class YUIPage : Page, IBasePage
	{
		private JavaScriptManager _scriptManager;
		private StyleSheetManager _cssManager;

		private bool _checkTimeoutEnabled = true;
		private bool _renderStyleSheetEnabled = true;
		private bool _renderClientScriptEnabled = true;

        public JavaScriptManager ScriptManager
		{
			get{ return _scriptManager; }
		}

		public StyleSheetManager StyleSheetManager
		{
			get{ return _cssManager; }
		}

        public YUIPage()
		{
		}

		public string ApplicationVirtualDirectory
		{
			get
			{
				string path = RequestContext.GetPageFileNameWithPath();

				string relativePath = string.Empty;
				if ( path.IndexOf("/") > -1 )
				{
					string[] dirArray = path.Split('/');
					int length = dirArray.Length - 1;
					while( length > 0 )
					{
						relativePath += "../";
						length--;
					}
				}
				else
				{
					relativePath = "./";
				}

				string script = "<script language=javascript><!--\n var m_ApplicationVirtualRelativePath = '" + relativePath + "';\n//--></script>";
				string key = "Key_ApplicationVirtualRelativePath";
				if (!Page.IsClientScriptBlockRegistered(key))
                    Page.RegisterClientScriptBlock(key, script);

				//Page.RegisterHiddenField("hdnApplicationVirtualDirectory", relativePath);
				return relativePath;
			}
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit (e);

			Initialize();

            Type baseType = this.GetType().BaseType;
            Utility.RegisterTypeForAjax(baseType);

			SetAttributes();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);			
		}


		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender (e);			
		}

		protected override void Render(HtmlTextWriter writer)
		{
			if (_renderStyleSheetEnabled)
				_cssManager.Render(writer, this.ApplicationVirtualDirectory, "Common");
			
			if (_renderClientScriptEnabled)
				_scriptManager.Render(writer, this.ApplicationVirtualDirectory, "Common");

			base.Render (writer);			
		}

		protected override void OnError(EventArgs e)
		{
			base.OnError (e);
			Exception exception = Server.GetLastError();			
			throw(exception);
		}


		private void Initialize()
		{
			string appVirtualDir = this.ApplicationVirtualDirectory;
			_scriptManager = new JavaScriptManager();
			_cssManager = new StyleSheetManager();
		}

		private void SetAttributes()
		{
			Type baseType = this.GetType().BaseType;
			object[] attributes = baseType.GetCustomAttributes(false);
			foreach(object attribute in attributes)
			{
				if( attribute is CheckTimeoutAttribute )
					_checkTimeoutEnabled = ((CheckTimeoutAttribute)attribute).Enabled;					
				else if (attribute is RenderClientScriptAttribute)
					_renderClientScriptEnabled = ((RenderClientScriptAttribute)attribute).Enabled;
				else if (attribute is RenderStyleSheetAttribute)
					_renderStyleSheetEnabled = ((RenderStyleSheetAttribute)attribute).Enabled;
			}

			if (_checkTimeoutEnabled)
			{
				int iTimestamp = int.Parse(DateTime.Now.ToString("HHmmss"));

				StringBuilder scriptBuilder = new StringBuilder();
				scriptBuilder.Append("<script language='javascript'><!--");
				//note: var in js is an integer (not quoted)
				scriptBuilder.Append(string.Format("\n var m_iLocalPageTimeoutTimestamp={0}; ", iTimestamp));
				//and finally add the actual (configurable) page timeout period (in ms)
				scriptBuilder.Append(string.Format("\n var m_iPageTimeout={0}; ", 900000));
				scriptBuilder.Append("\n//--></script>\n");

				//link in timeout js
				string jsPath = ((string[])JavaScriptManager.Scripts["Timeout"])[0];
				scriptBuilder.Append(string.Format("<script language='javascript' src='{0}" + jsPath + "'></script>\n", this.ApplicationVirtualDirectory));
				Response.Write(scriptBuilder.ToString());
			}
		}
	}
}
